package tools

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"fmt"
	"time"
	"strconv"
)

var (
	accessKey = "XKBReyz2LNWIaUhV"
	secretKey = "5UVC6NuE51nnKZBo"
)

func MsSign() string {
	var plainText = accessKey + "|" + strconv.FormatInt(time.Now().UnixNano() / 1e6, 10)

	encryptedData := AESEncrypt(plainText, []byte(secretKey))
	encryptedString := base64.StdEncoding.EncodeToString(encryptedData)
	//fmt.Println(encryptedString)

	encryptedData, _ = base64.StdEncoding.DecodeString(encryptedString)
	decryptedText := AESDecrypt(encryptedData, []byte(secretKey))
	sign := string(decryptedText)
	fmt.Println(sign)
	return sign
}

func AESEncrypt(src string, key []byte) []byte {
	block, err := aes.NewCipher(key)
	if err != nil {
		fmt.Println("key error1", err)
	}
	if src == "" {
		fmt.Println("plain content empty")
	}
	ecb := cipher.NewCBCEncrypter(block, []byte(accessKey))
	content := []byte(src)
	content = PKCS5Padding(content, block.BlockSize())
	crypted := make([]byte, len(content))
	ecb.CryptBlocks(crypted, content)

	return crypted
}

func AESDecrypt(crypt []byte, key []byte) []byte {
	block, err := aes.NewCipher(key)
	if err != nil {
		fmt.Println("key error1", err)
	}
	if len(crypt) == 0 {
		fmt.Println("plain content empty")
	}
	ecb := cipher.NewCBCDecrypter(block, []byte(accessKey))
	decrypted := make([]byte, len(crypt))
	ecb.CryptBlocks(decrypted, crypt)

	return PKCS5Trimming(decrypted)
}

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func PKCS5Trimming(encrypt []byte) []byte {
	padding := encrypt[len(encrypt)-1]
	return encrypt[:len(encrypt)-int(padding)]
}